import com.im30.jenkins.pipeline.utils.BuildConfig

def call() {
    properties([
            gitLabConnection('GitLab'),
            buildDiscarder(logRotator(artifactDaysToim30Str: '', artifactNumToim30Str: '', daysToim30Str: '7', numToim30Str: '50'))
    ])

    dockerNode.javaBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        try {
            stage('Notify Banana') {
                echo "remote config ${scm.userRemoteConfigs}"
                try {
                    // 通知 banana
                    def scmUrl = scm.userRemoteConfigs[0].getUrl()
                    status = sh(script: "curl https://banana.sre.gotoim30.com/builds/syncGit?repo=$scmUrl", returnStatus: true)
                    echo status
                } catch (err) {
                    echo err.message
                }
            }

            stage('Preparation') {
                // fetch remote tags
                checkout scm: [
                        $class           : 'GitSCM',
                        branches         : [[name: "origin/${env.gitlabSourceBranch}"]],
                        extensions       : [[$class: 'CloneOption', noTags: false, shallow: false, depth: 0, reference: '']],
                        userRemoteConfigs: scm.userRemoteConfigs
                ]
            }

            buildConfig = BuildConfig.load(this)
            if (buildConfig == null) {
                throw new Exception("Cannot parse build.yaml")
            }

            gitlabBuilds(builds: ['Build']) {

                // 编译通过后就触发 APP_ job 进行构建，提前 CI 打包时间
                stage('Build') {
                    gitlabCommitStatus("Build") {
                        if (buildConfig.isLibRepo()) {
                            echo 'Deploy to Maven'
                            mavenUtil.deployMavenInGitLab(buildConfig)
                        }

                        if (buildConfig.isAppRepo()) {
                            echo 'Build JAR and DockerImage'
                            jobUtil.buildApps(buildConfig)
                        }
                    }
                }
            }

        } finally {
            isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
            if (buildConfig != null) {
                notifyUtil.notifyRepo(buildConfig.getNotifyConfig(), jobUtil.getRepoName(), jobUtil.getBranchName(), isSuccess)
            }
            deleteDir()
        }
    }
}